import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.TimerTask;

public class Daemon extends TimerTask {
    static InetAddress ip;
    static int port;
    static int counter = 0;

    public Daemon(String host, String portStr) {
        super();
        try {
            ip = InetAddress.getByName(host);
            port = Integer.parseInt(portStr);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        updateStatus();
        Client.gameBoard.repaint();
    }

    static void sendKey(int keys) {
        try {
            Request req = new Request(Request.UPDATE_SELF);
            req.id = Client.playerID;
            req.move = keys;
            Socket s = new Socket(ip, port);
            OutputStream out = s.getOutputStream();
            out.write(req.toBytes());
            out.flush();
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static void updateStatus() {
        try {
            Request req = new Request(Request.GET_STATUS);
            Socket s = new Socket(ip, port);
            OutputStream out = s.getOutputStream();
            out.write(req.toBytes());
            out.flush();
            InputStream in = s.getInputStream();
            int len = Game.LEN;
            byte[] buf = new byte[len];
            int readlen = in.read(buf);
            while (readlen < len) {
                readlen += in.read(buf, readlen, len - readlen);
            }
            Client.game = new Game(buf);
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        Daemon daemon = new Daemon("192.168.1.7", "8008");
        joinGame("test");
        showStatus();
    }

    static void showStatus() {
        updateStatus();
        System.out.println("data received:" + Client.game);

    }

    static void joinGame(String name) {
        try {
            Request req = new Request(Request.JOIN_GAME);
            req.name = name;
            Socket s = new Socket(ip, port);
            OutputStream out = s.getOutputStream();
            out.write(req.toBytes());
            out.flush();

            InputStream in = s.getInputStream();
            int len = Player.LEN;
            byte[] buf = new byte[len];
            int readlen = in.read(buf);
            while (readlen < len) {
                readlen += in.read(buf, readlen, len - readlen);
            }
            Client.playerID = new Player(buf).id;
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
